package top.shiyiri;

import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * @author Aunean
 * @date 2022/1/15 22:37
 */
public class Java9Test {

    //Java9新特性：InputStream的新方法：tranferTo()
    @Test
    public void test() {
        ClassLoader cl = this.getClass().getClassLoader();
        try (InputStream is = cl.getResourceAsStream("hello.txt");
            OutputStream os = new FileOutputStream("src\\hello1.txt")) {
            is.transferTo(os); // 把输入流中的所有数据直接自动地复制到输出流中
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Java9新特性：Stream API 的加强
    @Test
    public void test1() {
        List<Integer> list = Arrays.asList(12, 23, 43, 54, 73, 4, 6, 58);
        //takeWhile：返回从开头开始的按照指定规则尽量多的元素
        //list.stream().takeWhile(x -> x < 60).forEach(System.out::println);

        //dropWhile()：与 takeWhile相反，返回剩余的元素
        //list.stream().dropWhile(x -> x < 60).forEach(System.out::println);
    }

    @Test
    public void test2() {
        //of()：参数中的多个元素，可以包含null值
        Stream<Integer> stream = Stream.of(12, 3, 4, null);
        //stream.forEach(System.out::println);

        //of()参数不能存储单个null值
        //Stream<Object> objectStream = Stream.of(null);
        //objectStream.forEach(System.out::println);

        Stream<Object> stream1 = Stream.ofNullable(null);
        //stream1.forEach(System.out::println);
        long count = stream1.count();
        System.out.println(count);//0
    }

    @Test
    public void test3() {
        //Java8
        Stream.iterate(0, x -> x + 1).limit(50).forEach(System.out::println);

        //java9：新增的重载的方法
        Stream.iterate(0, x -> x < 100, x -> x + 1).forEach(System.out::println);
    }

    //Java9新特性：Optional提供了新的方法 stream()
    @Test
    public void test4() {
        List<String> list = new ArrayList<>();
        list.add("Tom");
        list.add("Jerry");
        list.add("Tim");
        Optional<List<String>> optional = Optional.ofNullable(list);
        Stream<List<String>> stream = optional.stream();
        stream.flatMap(x -> x.stream()).forEach(System.out::println);
    }
}
